package com.google.bling.client.widget;

import java.util.Map;
import java.util.Map.Entry;

import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Image;

public class Chart extends Composite {
  private final static int WIDTH = 250;
  private final static int HEIGHT = 100;
  private final static String BASE_URL = "http://chart.apis.google.com/chart?";
  
  private final Image image = new Image();
  
  public Chart() {
    initWidget(image);
    image.setWidth("" + WIDTH);
    image.setHeight("" + HEIGHT);
    image.setVisible(false);
  }
  
  public void setData(Map<String, Integer> data) {
    String keys = "";
    String values = "";
    int total = 0;
    for (Integer i : data.values()) {
      total += i;
    }
    if(total==0) {
      image.setUrl("");
      image.setVisible(false);
      return;
    } else {
      image.setVisible(true);
    }
    for (Entry<String, Integer> e : data.entrySet()) {
      keys += e.getKey() + "|";
      values += ((e.getValue() * 100) / total) + ",";
    }
    keys = keys.substring(0, keys.length() - 1);
    values = values.substring(0, values.length() - 1);
    
    String url = BASE_URL;
    url += "chs=" + WIDTH + "x" + HEIGHT;
    url += "&";
    url += "chd=t:" + values;
    url += "&";
    url += "cht=p";
    url += "&";
    url += "chl=" + keys;
    image.setUrl(url);
    image.setTitle(url);
  }
}
